package com.atguigu.spzx.manager.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.manager.listener.ExcelCategoryListener;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.manager.service.CategoryService;
import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.excel.ExcelCategoryVo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {
    @Resource
    CategoryMapper categoryMapper;

    @Override
    public List<Category> listByParentId(Long pid) {

        List<Category> categories = categoryMapper.selectByParentId(pid);

        categories.forEach(category -> {
            //查询正在遍历的分类是否有下一级
            long count = categoryMapper.countChildren(category.getId());
            category.setHasChildren(count>0);
        });



//        log.info("日志级别：{} ,查询到的分类数据：{}" , "info",  categories);
//        log.debug("日志级别：{} ,查询到的分类数据：{}" , "debug",  categories);
//        log.warn("日志级别：{} ,查询到的分类数据：{}" , "warn",  categories);
//        log.error("日志级别：{} ,查询到的分类数据：{}" , "error",  categories);
        return categories;
    }
    //导出分类数据到excel
    @Override
    public void exportCates(HttpServletResponse response) {
        try {
            List<Category> categories = categoryMapper.selectList();
            //将查询到的category转为ExcelCategoryVo
            List<ExcelCategoryVo> vos = categories.stream().map(category -> {
                ExcelCategoryVo excelCategoryVo = new ExcelCategoryVo();
                //将category对象的属性值拷贝给ExcelCategoryVo对象相同名称+类型的 属性
                BeanUtils.copyProperties(category, excelCategoryVo);
                return excelCategoryVo;
            }).collect(Collectors.toList());
            //配置响应头：浏览器/客户端  解析响应体之前 可以判断如何读取
            //- 1、配置响应内容格式
            response.setContentType("application/vnd.ms-excel");
            //- 2、设置响应体内容字符编码
            response.setCharacterEncoding("UTF-8");
            //- 3、设置响应内容描述：告诉浏览器响应的是一个文件 + 文件名
            String fileName = "spzx_商品分类_"+new DateTime().toString("yyyy-MM-dd")+ ExcelTypeEnum.XLSX.getValue();
            fileName = URLEncoder.encode(fileName,"UTF-8");//防止浏览器中文文件名乱码
            response.setHeader("content-dispositon" ,"attachment;filename="+fileName);


            //将excel文件写入到响应体中
            EasyExcel.write(response.getOutputStream()) //输出流
                    .sheet("商品分类数据") //excel工作簿
                    .head(ExcelCategoryVo.class) //excel表头
                    .doWrite(vos); //excel数据
        } catch (Exception e) {
            throw new GuiguException(ResultCodeEnum.EXPORT_ERROR);
        }

    }
    /*
        解析excel文件
            每一行转为一个分类对象保存到数据库表中
     */
    @Override
    public void importCates(MultipartFile excel) {
        try {
            EasyExcel
                    .read(excel.getInputStream()) //解析提交的文件输入流
                    .sheet(0) //工作簿
                    .head(ExcelCategoryVo.class) //表头
                    .registerReadListener(new ExcelCategoryListener(categoryMapper)) // 注册读取监听器
                    .doRead();//开始读取
        } catch (Exception e) {
            throw new GuiguException(ResultCodeEnum.IMPORT_ERROR);
        }

    }
}
